package logic

import (
	"context"
	"encoding/json"

	"googee/common/errorx"
	"googee/common/tool"
	"googee/service/captcha/rpc/captcha"
	"googee/service/sms/rpc/types/sms"
	"googee/service/user/api/internal/svc"
	"googee/service/user/api/internal/types"
	"googee/service/user/rpc/user"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type SendcodeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSendcodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendcodeLogic {
	return &SendcodeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SendcodeLogic) Sendcode(req *types.BindPhoneCodeReq) (resp *types.BindPhoneCodeReply, err error) {
	resp = &types.BindPhoneCodeReply{}

	id, err := l.ctx.Value("userId").(json.Number).Int64()
	if err != nil {
		return nil, err
	}

	//查看我自己是否已经绑定了手机号
	u, _ := l.svcCtx.User.GetUser(l.ctx, &user.IdRequest{Id: id})
	if u.GetPhone() != "" {
		return nil, errorx.NewCodeErrorNoMsg(errorx.USER_ERROR + 11)
	}

	phone := req.Phone

	if !tool.VerifyMobileFormat(phone) {
		return nil, errorx.NewCodeErrorNoMsg(errorx.USER_ERROR + 4)
	}

	result, err := l.svcCtx.Captcha.Verify(l.ctx, &captcha.VerifyRequest{Key: phone, Value: req.ImgeCode})

	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			if st.Code() == codes.InvalidArgument {
				return nil, errorx.NewCodeErrorNoMsg(errorx.USER_ERROR + 4)
			} else if st.Code() == codes.Internal {
				return nil, errorx.NewCodeError(errorx.INTERNAL_ERROR, "系统内部未知错误")
			}
		} else {
			return nil, errorx.NewCodeError(errorx.INTERNAL_ERROR, "系统内部未知错误")
		}
	}

	if !result.Pass {
		_ = copier.Copy(&resp, errorx.NewCodeErrorNoMsg(errorx.USER_ERROR+8))
		return
	}

	//发送短信
	_, err = l.svcCtx.Sms.SendShortMessage(l.ctx, &sms.SendSmsRequest{
		Phone:   phone,
		Id:      id,
		Content: tool.Krand(4, tool.KC_RAND_KIND_NUM),
		Typ:     sms.SendSmsRequest_VERIFY,
	})

	logx.Info("--------------------------------\n")
	logx.Infof("err:%v\n", err)
	logx.Info("--------------------------------\n")
	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			if st.Code() == codes.InvalidArgument {
				return nil, errorx.NewCodeErrorNoMsg(errorx.USER_ERROR + 4)
			} else if st.Code() == codes.AlreadyExists {
				return nil, errorx.NewCodeErrorNoMsg(errorx.USER_ERROR + 9)
			} else {
				return nil, errorx.NewCodeError(errorx.INTERNAL_ERROR, "系统内部未知错误")
			}
		} else {
			return nil, errorx.NewCodeError(errorx.INTERNAL_ERROR, "系统内部未知错误")
		}
	}

	return
}
